<html>
<head>
    <title>商品管理</title>
    <!-- 引入layui框架的CSS样式 -->
    <link href="/lib/layui/css/layui.css" rel="stylesheet"/>
    <!-- 引入 css -->
    <link href="/css/wangeditor.css" rel="stylesheet">

    <style>
        #upload-demo-preview img{
            width: 90px;
            height: 90px;
            margin: 0 10px 10px 0;
        }
        #editor—wrapper {
            border: 1px solid #ccc;
            z-index: 100; /* 按需定义 */
        }
        #toolbar-container { border-bottom: 1px solid #ccc; }
        #editor-container { height: 500px; }
    </style>
</head>
<body>

<form class="layui-form" action="">
    <div class="layui-form-item" style="margin-top:15px">
        <div class="layui-inline">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-inline">
                <input id="input2" type="text" lay-affix="clear" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label">状态</label>

        </div>
        <div class="layui-inline">
            <div class="layui-input-inline">
                <select id="select1">
                    <option value="1">所有</option>
                    <option value="1">上架</option>
                    <option value="0">下架</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <button id="searchBtn" type="button" class="layui-btn">
                <i class="layui-icon layui-icon-search"></i>
                查询
            </button>
            <button id="addBtn" type="button" class="layui-btn">
                <i class="layui-icon layui-icon-add-circle"></i>
                新增
            </button>
            <button id="delBtn" type="button" class="layui-btn">
                <i class="layui-icon layui-icon-reduce-circle"></i>
                删除
            </button>
        </div>
    </div>
</form>

<table id="pTable"></table>

<!-- 弹出窗口的模版 -->
<script id="template1" type="text/html">
    <form class="layui-form" action="" lay-filter="form1" style="padding: 10px">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-inline">
                    <input type="hidden" name="id"/>
                    <input type="text" name="name" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">商品价格</label>
                <div class="layui-input-inline">
                    <input type="number" name="price" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">一级分类</label>
                <div class="layui-input-inline">
                    <select id="topSelect" lay-filter="topSelect"></select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">二级分类</label>
                <div class="layui-input-inline">
                    <select id="secondSelect" name="categoryId"></select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">

        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">版本</label>
                <div class="layui-input-inline">
                    <input type="text" name="edition" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">颜色</label>
                <div class="layui-input-inline">
                    <input type="text" name="color" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">标题</label>
                <div class="layui-input-inline">
                    <input type="text" name="title" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">主图</label>
                <div class="layui-input-inline">
                    <img id="avatarImg" width="50px" height="50px"/>
                    <input id="avatarInput" type="hidden" name="imgPath" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>

<!--        <div id="editor—wrapper">-->
<!--            <div id="toolbar-container">&lt;!&ndash; 工具栏 &ndash;&gt;</div>-->
<!--            <div id="editor-container">&lt;!&ndash; 编辑器 &ndash;&gt;</div>-->
<!--        </div>-->
<!--        <textarea name="description" id="description"></textarea>-->
        <div class="layui-form-item">
            <div class="layui-input-block">
                <input type="reset" value="重置" class="layui-btn layui-btn-primary"/>
                <input type="button" id="saveBtn" value="保存" class="layui-btn"/>
            </div>
        </div>
    </form>
</script>

<!-- 表格操作模版 -->
<script id="template2" type="text/html">
    <input lay-event="edit" type="button" class="layui-btn layui-btn-xs" value="编辑"/>
    <input lay-event="delete" type="button" class="layui-btn layui-btn-xs layui-bg-red" value="删除"/>
    <input lay-event="att" type="button" class="layui-btn layui-btn-xs layui-bg-orange" value="附件"/>
</script>

<!-- 状态切换模版 -->
<script id="ID-table-demo-templet-switch" type="text/html" th:inline="NONE">
    <input type="checkbox" name="status" value="{{=d.id }}" title="上架|NO" lay-skin="switch" lay-filter="demo-templet-status" {{= d.status==1?"checked":"" }}>
</script>



<script id="template3" type="text/html">
    <div class="layui-upload">
        <button type="button" class="layui-btn" id="ID-upload-demo-btn-2">
            <i class="layui-icon layui-icon-upload"></i> 多图片上传
        </button>
        <div class="layui-upload-list" id="upload-demo-preview"></div>
    </div>
</script>

<script src="/lib/layui/layui.js"></script>
<script src="/js/common.js"></script>
<!-- 引入 js -->
<script src="/js/wangeditor.js"></script>

<script type="text/javascript" th:inline="none">
    //告诉浏览器加载layui框架中的哪些组件
    //加载完小组件　就执行function
    layui.use(['table', 'layer', 'form', 'upload'], function () {
        var table = layui.table;
        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form;
        var upload = layui.upload;

        //批量删除
        $("#delBtn").on("click", function () {
            var o = table.checkStatus("pTable");
            if (o.data.length === 0) {
                layer.msg("至少选中一行");
                return false;
            }
            layer.confirm("您确定要删除选中的商品吗？", function () {
                var ids = "";
                $.each(o.data, function (index, item) {
                    if (ids) {
                        ids += ",";
                    }
                    ids += item.id;
                });
                $.post("/product/delete", {ids: ids}, function () {
                    layer.closeAll();
                    layer.msg("删除成功");
                    $("#searchBtn").click();
                });
            });
        });

        //给查询按钮绑定事件
        $("#searchBtn").on("click", function () {
            //用js发起一个请求去要一些数据回来，要到之后把数据插入到table中
            //通过table组件渲染表格
            table.render({
                elem: "#pTable",
                url: "/product/list",
                cols: [[
                    {title: "选择", type: "checkbox"},
                    {title: "序号", type:"numbers"},
                    {title: "商品名称", field: "name"},
                    {title: "版本", field: "edition"},
                    {title: "分类", field: "categoryName"},
                    {title: "颜色", field: "color"},
                    {title: "价格", field: "price"},
                    {title: '状态', width:90, templet: '#ID-table-demo-templet-switch'},
                    {title: "操作", templet: "#template2"}
                ]],
                where: {name: $("#input2").val(), status: $("#select1").val()},
                page: true,
                limits: [5, 10, 20],
                limit: 10
            });
        }).click();

        //给切换状态绑定事件
        form.on('switch(demo-templet-status)', function(obj){
            console.log(obj.value);//要根据的商品的ID
            console.log(obj.elem.checked);//true就是上架，false就是下架
            $.post("/product/status",{id:obj.value,status:obj.elem.checked?1:0},function(){
                layer.msg("更新状态成功");
            });
        });

        //根据一级分类的选项加载二级分类
        var loadCategory = function (f){
            //获取一级下拉框的ID
            var topId=  $("#topSelect").val();
            $.get("/category/children?id="+topId,function(children){
                //清空原来二级分类的所有option
                $("#secondSelect").html("");
                $.each(children,function(index,item){
                    $("#secondSelect").append("<option value='"+item.id+"'>"+item.name+"</option>")
                });
                form.render();
                if(f){
                    f();
                }

            });
        };

        //给新增按钮绑定事件
        $("#addBtn").on("click", function () {
            //发请求获取所有的顶级分类
            $.get("/category/children?id=0",function(tops){
                layer.open({
                    title: "新增商品",
                    type: 1,
                    area: ['900px', '600px'],
                    maxmin:true,
                    content: $("#template1").html()
                });
                $.each(tops,function(index,item){
                    $("#topSelect").append("<option value='"+item.id+"'>"+item.name+"</option>");
                });
                form.render();
                loadCategory();

                form.on("select(topSelect)",function(){
                    loadCategory();
                });
                upload.render({
                    elem: "#avatarImg",
                    url: "/attachment/upload",
                    done: function (res, index, upload) {
                        if (res.code === 0) {
                            $("#avatarInput").val(res.data);
                            $("#avatarImg").attr("src", res.data);
                        }
                    }
                });
                const { createEditor, createToolbar } = window.wangEditor
                const editorConfig = {
                    placeholder: 'Type here...',
                    onChange(editor) {
                        const html = editor.getHtml()
                        $("#description").val(html);
                    },
                    MENU_CONF:{}
                }
                editorConfig.MENU_CONF['uploadImage'] = {
                    server: '/attachment/editorUpload',
                    fieldName: 'file',
                    onSuccess:function (res){
                        console.log(res)
                    }
                }
                const editor = createEditor({
                    selector: '#editor-container',
                    html: '<p><br></p>',
                    config: editorConfig,
                    mode: 'default', // or 'simple'
                })

                const toolbarConfig = {}
                const toolbar = createToolbar({
                    editor,
                    selector: '#toolbar-container',
                    config: toolbarConfig,
                    mode: 'default', // or 'simple'
                })
            });


        });

        //新增和编辑的保存
        $("body").on("click", "#saveBtn", function () {
            var data = form.val("form1");
            $.post("/product/save", data, function () {
                if(!data.name){
                    layer.msg("商品名称不能为空");
                }
                layer.closeAll();
                layer.msg("保存成功");
                $("#searchBtn").click();
            });
        });

        //给表格操作绑定事件
        table.on("tool", function (obj) {
            var event = obj.event;
            var data = obj.data;
            if (event === "edit") {
                $.get("/product/" + data.id, function (product) {
                    $.get("/category/children?id=0",function(tops){
                        layer.open({
                            title: "编辑商品",
                            type: 1,
                            area: ['400px', '500px'],
                            content: $("#template1").html()
                        });
                        $.each(tops,function(index,item){
                            $("#topSelect").append("<option value='"+item.id+"'>"+item.name+"</option>");
                        });
                        //加载二级之前　回显一级分类数据
                        $("#topSelect").val(product.topCategory);

                        loadCategory(function(){
                            form.val("form1", product);
                        });

                    });
                });
            }
            if (event === "delete") {//说明点了删除
                layer.confirm("您确定要删除这个商品吗？", function () {
                    $.post("/product/delete", {ids: data.id}, function () {
                        layer.closeAll();
                        layer.msg("删除成功");
                        $("#searchBtn").click();
                    });
                });
            }
            if(event === "att"){

                //查之前上传过的附件　再弹出窗口　回显
                $.get("/product/attachment/"+data.id,function(atts){

                    layer.open({
                        type:1,
                        area:["400px","400px"],
                        title:"商品附件",
                        content:$("#template3").html()
                    });
                    if(atts!=null && atts.length >0){
                        $.each(atts,function(i,v){
                            $('#upload-demo-preview').append('<img id="'+v.id+'" src="'+ v.filePath +'"/>')
                        });
                    }
                    var attIds = "";
                    // 多图片上传
                    upload.render({
                        elem: '#ID-upload-demo-btn-2',
                        url: '/attachment/upload',
                        multiple: true,
                        before: function(obj){
                            obj.preview(function(index, file, result){
                                $('#upload-demo-preview').append('<img src="'+ result +'"/>')
                            });
                        },
                        done: function(res){
                            if(attIds){
                                attIds+=",";
                            }
                            attIds+=res.data.id;
                        },
                        allDone: function(){
                            //把上传的文件更新给这个商品
                            $.post("/product/bind",{id:data.id,attIds:attIds});
                        }
                    });
                    $("#upload-demo-preview img").on("dblclick",function(){
                        layer.confirm("确定要删除此附件吗？",function(){

                        }) ;
                    });
                });
            }
        });
    });
</script>
</body>
</html>
